<template>
    <!-- 三级分类全局组件 -->
    <Category :scene="scene" />

    <el-card style="margin:10px 0px">
        <div v-show="scene == 0">
            <el-button @click="addAttr" type="primary" size="default" icon="Plus"
                :disabled="categoryStore.c3Id ? false : true">添加属性</el-button>
            <el-table border style="margin:10px 0px" :data="attrArr">
                <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
                <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
                <el-table-column label="属性值名称">
                    <template #="{ row }">
                        <el-tag style="margin: 5px;" v-for="item in row.attrValueList" :key="item.id">{{ item.valueName
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120px">
                    <template #="{ row }">
                        <el-button type="primary" size="small" icon="Edit" @click="updateAttr(row)"></el-button>
                        <el-popconfirm :title="`您确定要删除${row.attrName}吗？`" width="200px" @confirm="deleteAttr(row.id)">
                            <template #reference>
                                <el-button type="primary" size="small" icon="Delete"></el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <div v-show="scene == 1">
            <el-form :inline="true">
                <el-form-item label="属性名称">
                    <el-input placeholder="请您输入属性名称" v-model="attrParams.attrName"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="addAttrValue" :disabled="attrParams.attrName ? false : true" type="primary" size="default"
                icon="Plus">添加属性值</el-button>
            <el-button type="primary" size="default" @click="cancel">取消</el-button>
            <el-table border style="margin:10px 0px" :data="attrParams.attrValueList">
                <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
                <el-table-column label="属性值名称">
                    <template #="{ row, $index }">
                        <el-input :ref="(vc: any) => inputArr[$index] = vc" @blur="toLock(row, $index)" size="small"
                            v-if="row.flag" v-model="row.valueName" placeholder="请您输入属性值名称"></el-input>
                        <div @click="toEdit(row, $index)" v-else>{{ row.valueName }}</div>
                    </template>
                </el-table-column>
                <el-table-column label="属性值操作">
                    <template #="{ $index }">
                        <el-button type="primary" size="small" icon="Delete"
                            @click="attrParams.attrValueList.splice($index, 1)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-button type="primary" size="default" @click="save"
                :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
            <el-button type="primary" size="default" @click="cancel">取消</el-button>
        </div>
    </el-card>
</template>

<script setup lang="ts">
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue';
import { reqAttr, reqAddOrUpdateAttr, reqRemoveAttr } from '@/api/product/attr'
import useCategoryStore from '@/store/modules/category'
import { ElMessage } from 'element-plus';
let categoryStore: any = useCategoryStore()
// 存储已有的属性和属性值
let attrArr = ref([])
// 定义场景切换的变量
let scene = ref(0)
// 定义空数组存储对应组件实例el-input
let inputArr: any = ref([])
// 收集新增的属性的数据
let attrParams: any = reactive({
    attrName: '',
    attrValueList: [],
    categoryId: '',
    categoryLevel: 3
})
watch(() => categoryStore.c3Id, () => {
    attrArr.value = []
    // 保证三级id得有了才能发送请求
    if (!categoryStore.c3Id) return
    getAttr()
})
// 获取已有属性和属性值的方法
const getAttr = async () => {
    const { c1Id, c2Id, c3Id } = categoryStore
    let result = await reqAttr(c1Id, c2Id, c3Id)
    if (result.code == 200) {
        attrArr.value = result.data
    }
}
// 添加属性按钮的回调
const addAttr = () => {
    Object.assign(attrParams, {
        attrName: '',
        attrValueList: [],
        categoryId: categoryStore.c3Id,
        categoryLevel: 3
    })
    scene.value = 1
}
// 修改已有属性按钮的回调
const updateAttr = (row: any) => {
    scene.value = 1
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 取消按钮的回调
const cancel = () => {
    scene.value = 0
}
// 添加属性值按钮的回调
const addAttrValue = () => {
    attrParams.attrValueList.push({
        valueName: '',
        flag: true
    })
    nextTick(() => {
        inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
}
// 保存按钮的回调
const save = async () => {
    let result = await reqAddOrUpdateAttr(attrParams)
    if (result.code == 200) {
        scene.value = 0
        ElMessage({ type: 'success', message: attrParams.id ? '修改成功' : '添加成功' })
        getAttr()
    } else {
        ElMessage({ type: 'error', message: attrParams.id ? '修改失败' : '添加失败' })
    }
}
// 属性值表单元素失去焦点的回调
const toLock = (row: any, $index: any) => {
    // 非法情况判断
    if (row.valueName.trim() == '') {
        attrParams.attrValueList.splice($index, 1)
        ElMessage({ type: 'error', message: '属性值不能为空' })
        return
    }
    let repeat = attrParams.attrValueList.find((item: any) => {
        if (item != row) {
            return item.valueName === row.valueName
        }
    })
    if (repeat) {
        attrParams.attrValueList.splice($index, 1)
        ElMessage({ type: 'error', message: '属性值不能重复' })
        return
    }
    row.flag = false
}
// 属性值div点击事件的回调
const toEdit = (row: any, $index: any) => {
    row.flag = true
    nextTick(() => {
        inputArr.value[$index].focus()
    })
}
// 删除已有属性的事件回调
const deleteAttr = async (attrId: any) => {
    let result = await reqRemoveAttr(attrId)
    if (result.code == 200) {
        ElMessage({ type: 'success', message: '删除成功' })
        getAttr()
    } else {
        ElMessage({ type: 'error', message: '删除失败' })
    }
}
// 路由组件销毁的时候，清空仓库对象的数据清空
onBeforeUnmount(() => {
    categoryStore.$reset()
})
</script>

<style scoped></style>